package com.gupaoedu.vip.pattern.proxy.dbroute.proxy;

import com.gupaoedu.vip.pattern.proxy.dbroute.Order;
import com.gupaoedu.vip.pattern.proxy.dbroute.db.DynamicDataSourceEntity;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;

public class CglibProxyOrderService implements MethodInterceptor {

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy");

    public Object getInstance(Class<?> clazz){
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(this);
        return enhancer.create();
    }

    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        Order order = (Order) objects[0];
        for (Object obj : objects) {
            System.out.println( obj.getClass().getMethod("getCreateTime",null).invoke(obj));
        }
        this.changeDbSource(Integer.valueOf(sdf.format(order.getCreateTime())));
        Object obj = methodProxy.invokeSuper(o,objects);
        this.restoreDbSource("1");
        return obj;
    }

    public void changeDbSource(int year){
        System.out.println("切换数据源");
        DynamicDataSourceEntity.set(year);
    }

    public void restoreDbSource(String source){
        System.out.println("恢复数据源");
        DynamicDataSourceEntity.set(source);
    }

}
